package com.guyaogg.gulimall.testssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 顾遥
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录就可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){

        return "hello";
    }

    /**
     * 感知 server 中登录成功跳回的
     * @param model
     * @param session
     * @param token 登录成功跳回来就会携带
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token, HttpServletRequest request){

        if(!ObjectUtils.isEmpty(token)){
            // 有 token 去 server 查询到用户,放入 session
            session.setAttribute("loginUser","zhangsan");
        }
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null){
            // 没登陆 ， 跳转到登录服务器登录
            return "redirect:"+ssoServerUrl + "?redirect_url=http://client1.com:8081/employees";
        }else {
            List<String> emps = new ArrayList<>(List.of("张三", "李四"));
            model.addAttribute("emps", emps);
            return "list";
        }

    }
}
